'use strict';

const Service = require('egg').Service;
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

class UserService extends Service {
  // 用户列表
  async page(query) {
    const { ctx } = this;
    let config = {
      where:{
        isDel:0
      },
      order:[
        ['createTime', 'DESC']
      ],
      attributes: {
        include: [
          [
            Sequelize.literal(`(
                  SELECT COUNT(*)
                  FROM collection
                  WHERE
                      collection.uid = user.id
              )`),
            'collectionNum'
          ],
          [
            Sequelize.literal(`(
                  SELECT COUNT(*)
                  FROM likes
                  WHERE
                      likes.uid = user.id
              )`),
            'likesNum'
          ],
          [
            Sequelize.literal(`(
                  SELECT COUNT(*)
                  FROM comment
                  WHERE
                      comment.uid = user.id
                      AND
                      comment.isDel = 0
              )`),
            'commentNum'
          ],
          [
            Sequelize.literal(`(
                  SELECT COUNT(*)
                  FROM playlist
                  WHERE
                      playlist.uid = user.id
                      AND
                      playlist.isDel = 0
              )`),
            'playlistNum'
          ]
        ],
        exclude: ['isDel','delTime','password'],
      }
    };
    if(query.account){
      config.where.account = query.account;
    }
    if(query.nickname) {
      config.where.nickname = {
        [Op.like]: `%${query.nickname}%`
      }
    }
    if(!query.pageNO){
      query.pageNO = 1;
    }
    if(!query.pageSize){
      query.pageSize = 10;
    }
    config.offset = (query.pageNO-1)*query.pageSize;
    config.limit = query.pageSize;
    return await ctx.model.User.findAndCountAll(config);
  }

  // 用户详情
  async detail(query) {
    const { ctx } = this;
    let config = {
      where:{
        isDel:0,
        id:query.id
      },
      attributes: {
        include: [
          [
            Sequelize.literal(`(
                  SELECT COUNT(*)
                  FROM collection
                  WHERE
                      collection.uid = user.id
              )`),
            'collectionNum'
          ],
          [
            Sequelize.literal(`(
                  SELECT COUNT(*)
                  FROM likes
                  WHERE
                      likes.uid = user.id
              )`),
            'likesNum'
          ],
          [
            Sequelize.literal(`(
                  SELECT COUNT(*)
                  FROM comment
                  WHERE
                      comment.uid = user.id
                      AND
                      comment.isDel = 0
              )`),
            'commentNum'
          ],
          [
            Sequelize.literal(`(
                  SELECT COUNT(*)
                  FROM playlist
                  WHERE
                      playlist.uid = user.id
                      AND
                      playlist.isDel = 0
              )`),
            'playlistNum'
          ]
        ],
        exclude: ['isDel','delTime','password']
      }
    };
    return await ctx.model.User.findOne(config);
  }

  // 用户删除
  async del(data) {
    const { ctx } = this;
    const t = await ctx.model.transaction();
    try{
      let [collectionDel,likeDel,commentDel,userDel] = await Promise.all(
        [
          // 删除收藏
          ctx.model.Collection.destroy({
            where: {
              uid:data.id
            },
            transaction:t
          }),
          // 删除点赞
          ctx.model.Likes.destroy({
            where: {
              uid:data.id
            },
            transaction:t
          }),
          // 删除评论
          ctx.model.Comment.update({
            isDel:1,
            delTime:new Date().getTime()
          },{
            where:{
              uid:data.id
            },
            transaction:t
          }),
          // 删除歌单
          ctx.model.Playlist.update({
            isDel:1,
            delTime:new Date().getTime()
          },{
            where:{
              uid:data.id
            },
            transaction:t
          }),
          // 删除用户
          ctx.model.User.update({
            isDel:1,
            delTime:new Date().getTime()
          },{
            where:{
              id:data.id
            },
            transaction:t
          })
        ]
      );
      if(!userDel[0]){
        throw new Error('error');
      }
      await t.commit();
      return userDel;
    }catch(e){
      await t.rollback();
      return [0];
    }
  }

  // 用户修改状态
  async status(data) {
    const { ctx } = this;
    return await ctx.model.User.update({
      status:data.status,
      updateTime:new Date().getTime()
    },{
      where:{
        id:data.id
      }
    });
  }

  // 获取用户总数
  async getNum() {
    const { ctx } = this;
    return await ctx.model.User.findOne({
      attributes: [
        [
          Sequelize.literal(`(
                  SELECT COUNT(*)
                  FROM user
                  WHERE
                      user.isDel = 0
              )`),
          'num'
        ]
      ]
    });
  }
}

module.exports = UserService;
